import React from 'react'

import Han from '../../components'
const {  Header,Button, Input} = Han

export default class Login extends React.Component {
    state={
        user:'',
        pwd:'',
        LoginStatus:true
    }
    submit = () =>{
        const {user,pwd,LoginStatus} = this.state;
        const {$httpReq} = this;
        const {USER_LOGIN,USER_REGISTER} =this.$api;
        // 非空检验
        if(user === '') return alert('用户名不能为空')
        if(pwd === '') return alert('密码不能为空')

        // 格式校验

        if(!/^[a-z0-9]{6,18}$/.test(user)) return alert('用户名不合法')
        if(!/^(?=.*[a-z])(?=.*[0-9])[^]{6,18}$/.test(pwd)) return alert('密码不合法')

        // 数据请求
        // 数据请求接口 登录或注册
        
        let apiFunc = LoginStatus?USER_LOGIN:USER_REGISTER;

        // 接口调用逻辑
        $httpReq(apiFunc({user,pwd}),res =>{
            // 登录成功
            if(LoginStatus){ 
                localStorage.user = user;
                this.props.history.push('/home')
                return 
            } 
            // 注册成功切换登录
            alert(res.msg)
            this.setState({LoginStatus:true})
        })
    }
    render() {
        const {user,pwd,LoginStatus} = this.state
        return (
            <div className="login">

                {/* 头 */}
                <Header title="欢迎来到健康宝！请登录" path="/home"/>

                {/* 身体 */}
                <div className="content">
                    <Input model="gray" label="登录账号" value={user} change={ value => this.setState({user:value})}/>
                    <Input model="gray" label="登录密码" type="password" value={pwd} change={ value => this.setState({pwd:value})}/>
                    <Button submit={this.submit} text={LoginStatus?'登录':'注册'}/>
                </div>

               {/* 尾部文案 */}
                <p onClick={()=>this.setState({LoginStatus:!LoginStatus})}>{LoginStatus?'没有账号去注册':'已有账号，去登录'}</p>
            </div>
        )
    }
}
